package com.hmall.user.interceptors;


import com.hmall.user.utis.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("authorization");
        if (StringUtils.isBlank(authorization)){
            log.warn("非法用户访问,请求路径是"+request.getRequestURI());
            //没用户信息就禁止
            response.setStatus(403);
            return false;
        }
        Long id = Long.valueOf(authorization);
        //存到TreadLocal
        UserHolder.setUser(id);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //用完记得清除
        UserHolder.removeUser();
    }
}
